import { OrderType } from '@/enums'
import { cancelOrderAPI, delOrderAPI, getPrePicAPI } from '@/services/consult'
import { getMedicalOrderDetailAPI } from '@/services/order'
import type { ConsultOrderItem } from '@/types/consult'
import type { OrderDetail } from '@/types/order'
import { showImagePreview, showToast } from 'vant'
import { onMounted, ref } from 'vue'

export const usePreview = () => {
  const onPreView = async (id: string) => {
    const res = await getPrePicAPI(id)
    showImagePreview([res.data.url])
  }

  return { onPreView }
}

export const useCancel = () => {
  const loading = ref(false)
  const onCancel = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await cancelOrderAPI(item.id)
      loading.value = false
      showToast('取消订单成功')
      item.status = OrderType.ConsultCancel
      item.statusValue = '取消订单'
    } catch (error) {
      loading.value = false
    }
  }

  return { loading, onCancel }
}

export const useDel = (cb: any) => {
  const delLoading = ref(false)

  const onDel = async (id: string) => {
    try {
      delLoading.value = true
      await delOrderAPI(id)
      delLoading.value = false
      showToast('删除成功')
      cb()
    } catch (error) {
      delLoading.value = false
    }
  }

  return {
    delLoading,
    onDel
  }
}

export const useOrderDetail = (id: string) => {
  const order = ref<OrderDetail>()
  const loadData = async () => {
    const { data } = await getMedicalOrderDetailAPI(id)
    order.value = data
  }

  onMounted(loadData)

  return {
    detail: order
  }
}
